<!--  -->
<template>
  <div id="detail" class="maxbg" v-cloak>
    <transition name="fade">
      <div class="pageBody">
        <div class="dt-top">
          <div class="logo"></div>
          <div class="down-btn" @click="linkCourse">下载APP</div>
        </div>
        <div class="dt-header">
          <div class="banner" v-if="courseData.cover">
            <img :src="isCover(courseData.cover)" />
          </div>
          <div class="dt-infor">
            <div class="dt-tl">{{ courseData.name }}</div>
            <div class="tag-box">
              <template v-for="item in courseData.tagNameList">
                <div class="tag-item">{{ item }}</div>
              </template>
            </div>
            <div class="dt-money">
              <span v-if="courseData.accessMode == 1" class="price">免费</span>
              <div
                class="price-item"
                v-else-if="
                  courseData.accessAuth != 1 && courseData.payText != 'VIP免费'
                "
              >
                <span class="price">{{ courseData.price / 1000 }}</span>
                <span class="price-tx">芝士</span>
              </div>
              <span
                v-else-if="courseData.accessMode == 4 && courseData.accessAuth != 1"
                class="price"
                >VIP限免</span
              >
              <div class="learn">已有{{ courseData.learnCount }}人学习</div>
            </div>
            <div class="dt-line"></div>
            <div class="dt-tm-box">
              <div class="dt-time">有效期{{ courseData.expiryDateText }}</div>
              <div class="dt-count">{{ courseData.chapterCount }}课时</div>
            </div>
          </div>
        </div>
        <div class="dt-main">
          <div class="dt-tabs">
            <div class="no-fixed" :class="showtab ? 'to-fixed' : ''">
              <div
                class="tabs"
                :class="tabIdx == 1 ? 'on' : ''"
                @click="tabIdx = 1"
              >
                详情
              </div>
              <div
                class="tabs"
                :class="tabIdx == 2 ? 'on' : ''"
                @click="tabIdx = 2"
              >
                目录
              </div>
            </div>
          </div>
          <div class="dt-ct">
            <template v-if="tabIdx == 1">
              <div class="introduce-tx" v-html="courseData.introduce"></div>
            </template>
            <template v-if="tabIdx == 2">
              <div class="directory dc-box">
                <template v-for="(item, index) in directoryList" :key="index">
                  <div
                    class="directory-group"
                    :class="showList[index] ? '' : 'arrow'"
                  >
                    <div
                      class="directory-title"
                      @click="showChapter(item.id, index)"
                    >
                      <span>{{ item.name }}</span>
                      <span class="arrow"></span>
                    </div>
                    <template v-if="item.children">
                      <div
                        class="sub-box"
                        :class="showList[index] ? '' : 'hide'"
                        v-for="(cItem, i) in item.children"
                        :key="i"
                      >
                        <div class="directory-subtitle">{{ cItem.name }}</div>
                        <template v-if="cItem.children">
                          <div
                            class="directory-content"
                            v-for="(kjItem, kjIndex) in cItem.children"
                            :key="kjIndex"
                          >
                            <!-- <div class="directory-tag" >
                                {{ kjItem.typeText }}
                              </div> -->
                            <div
                              class="directory-tx"
                              @click="goToPage(kjItem, cItem.id, item.id)"
                            >
                              {{ kjItem.name }}
                            </div>
                            <div class="directory-infor">
                              <div
                                class="directory-tag"
                                :class="getClass(kjItem)"
                              >
                                {{ kjItem.typeText }}
                              </div>
                              <div
                                class="directory-tag time"
                                v-if="
                                  kjItem.duration != 0 &&
                                  kjItem.duration != null
                                "
                              >
                                {{ getTime(kjItem.duration) }}
                              </div>
                              <div
                                class="directory-tag size"
                                v-if="
                                  kjItem.fileSize != 0 &&
                                  kjItem.fileSize != null
                                "
                              >
                                {{ sizeTostr(kjItem.fileSize) }}
                              </div>
                              <!-- <div class="directory-tag learn">
                                  {{ kjItem.learned == false ? "待学习" : "" }}
                                </div> -->
                            </div>
                            <span class="tip" v-if="kjItem.trySee == 1"
                              >试看</span
                            >
                          </div>
                        </template>
                        <!-- <div class="directory-line"></div> -->
                      </div>
                    </template>
                  </div>
                </template>
              </div>
            </template>
          </div>
        </div>
        <div class="vip-box" v-if="!isUserInfoComplete && loginState">
          <div class="vip-inf-img"></div>
          <div class="vip-tl">赠送7天会员，享88折优惠！</div>
          <div class="vip-btn" @click="gotoInforPage">立即完善</div>
        </div>
        <div
          class="vip-box"
          v-if="courseData.accessAuth !== 1 && loginState && isUserInfoComplete"
        >
          <div class="vip-img"></div>
          <div class="vip-tl" v-if="isVip">会员到期时间{{ time }}</div>
          <div class="vip-tl" v-else>VIP会员享受85折优惠！</div>
          <div class="vip-btn" v-if="isVip" @click="gotoPay">会员续费</div>
          <div class="vip-btn" v-else-if="!isVip && courseData.specialOffer==2" @click="payCrouse(courseData.specificationId)">立即购买</div>
          <div class="vip-btn" v-else @click="gotoPay">开通会员</div>
        </div>
        <div class="dt-foot" v-if="!loginState">
          <div class="ft-tip">
            <div class="tip-tx">请先下载APP再打开课程，体验会更好</div>
          </div>
          <div class="ft-btn" @click="payCrouse(courseData.specificationId)">
            立即购买
          </div>
        </div>
        <div class="dt-foot-service order-bt-gp" v-else>
          <div class="service" id="service">客服</div>
          <template v-if="courseData.accessAuth !== 1">
            <div class="login-btn" v-if="!isVip && courseData.accessMode === 4 && courseData.specialOffer != 2">
              开通会员
            </div>
            <div
              class="login-btn"
              v-else-if="courseData.accessMode === 2"
              @click="payCrouse(courseData.specificationId)"
            >
              <span v-if="courseData.specialOffer==1"
                >折扣价{{ courseData?.discountPrice / 1000 }}芝士&nbsp;</span
              >立即购买
            </div>
          </template>
          <template v-else>
            <div class="login-btn" @click="isApp = true">参与学习</div>
          </template>
        </div>
      </div>
    </transition>
    <!-- <div class="box-app">
        <div class="downloadButton" @click="linkCourse">下载课程</div>
      </div> -->
  </div>
  <div class="mask" v-if="isApp">
    <div class="modal">
      <div class="moadl-tl">提示</div>
      <div class="modal-tx">请前往APP学习</div>
      <div class="modal-btn" @click="linkCourse">知道了</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      openData: {},
      courseData: {},
      tabIdx: 1,
      directoryList: [],
      idList: [],
      itemList: [{}, {}],
      showList: [],
      showtab: false,
      num: 0,
      rnum: 0,
      loginState: false,
      isVip: false,
      isApp: false,
      time: "",
      isUserInfoComplete: false,
    };
  },
  components: {},
  created() {
    this.isVip = JSON.parse(localStorage.getItem("isVip"));
    this.time = localStorage.getItem("vipTime")?.replaceAll("/", "-");
  },
  mounted() {
    // this.alertmess('页面进来了')
    this.init();
    this.btnType();
    this.getCourseDetail();
    this.getCourseChapterList();
    this.getUserCompleteInfo();
    window.addEventListener("scroll", this.scrolling);
  },
  methods: {
    getUserCompleteInfo() {
      this.$http
        .getUserCompleteInfo()
        .then(async (res) => {
          if (res.flag === 0) {
            this.isUserInfoComplete = res.data == 0 ? false : true;
          }
        })
        .catch((err) => {
          // this.$Message.error(err.response.data.message);
        });
    },
    gotoInforPage() {
      const actionType = this.$route.query.actionType;
      const code = this.$route.query.invitationCode
        ? this.$route.query.invitationCode
        : "";
      const type = this.$route.query.type ? this.$route.query.type : "";
      const info = { actionType: actionType, invitationCode: code, type: type,idx:1 };
      // localStorage.setItem("userInfo", JSON.stringify(userInfo));
      this.$router.push({
        path: "/myinformation",
        query: {
          actionType: actionType,
          invitationCode: code,
          type: type,
        },
      });
    },
    gotoPay() {
      const actionType = this.$route.query.actionType;
      const code = this.$route.query.invitationCode
        ? this.$route.query.invitationCode
        : "";
      const type = this.$route.query.type ? this.$route.query.type : "";
      this.$router.push({
        path: "/vip",
        query: {
          actionType: 4,
          invitationCode: code,
          type: type,
        },
      });
    },
    payCrouse(specificationId) {
      if(!this.loginState){
        this.$router.push({
          path: "/login",
        });
      }else{
        const courseId = this.$route.query.id;
        const code = this.$route.query.invitationCode
          ? this.$route.query.invitationCode
          : "";
        const actionType = this.$route.query.actionType;
        const type = this.$route.query.type ? this.$route.query.type : "";
        this.$router.push({
          path: "/crouse/pay",
          query: {
            courseId: courseId,
            specificationId: specificationId,
            showType: 1,
            invitationCode: code,
            actionType: actionType,
            type: type,
          },
        });
      }
    },
    btnType() {
      const token = localStorage.getItem("access_token");
      if (token && token != null && token != "null") {
        this.loginState = true;
      }
    },
    scrolling() {
      // const top = $(".dt-tabs").offset().top - 40;
      // // 滚动条距文档顶部的距离
      // let scrollTop =
      //   window.pageYOffset ||
      //   document.documentElement.scrollTop ||
      //   document.body.scrollTop;
      // // 滚动条滚动的距离
      // if (scrollTop > top) {
      //   this.showtab = true;
      // } else {
      //   this.showtab = false;
      // }
      this.$forceUpdate();
    },
    showChapter(id, idx) {
      this.showList[idx] = !this.showList[idx];
      if (this.idList.indexOf(id) == -1) {
        this.idList.push(id);
        this.getChapterList(id);
      }
      this.$forceUpdate();
    },
    getCourseDetail() {
      const courseId = this.$route.query.id;
      this.$http
        .getCourseV2Detail(courseId)
        .then(async (res) => {
          if (res.flag === 0) {
            this.courseData = res.data || {};
            document.title = res.data.name;
          }
        })
        .catch((err) => {
          // this.$Message.error(err.response.data.message);
        });
    },
    // 获取课程目录
    getCourseChapterList() {
      const courseId = this.$route.query.id;
      this.$http
        .getCourseChapterList(courseId)
        .then(async (res) => {
          if (res.flag === 0) {
            localStorage.setItem("chapterList", JSON.stringify(res.data));
            this.directoryList = await this.getTree(res.data);
            this.getChapterList(this.directoryList[0].id);
            this.idList.push(this.directoryList[0].id);
            this.itemList = this.directoryList;
            this.showList = new Array(this.directoryList.length);
            this.showList[0] = true;
          }
        })
        .catch((err) => {
          // this.$Message.error(err.response.data.message);
        });
    },
    getChapterList(id) {
      const params = { chapterId: id };
      this.$http
        .getCoursewareChapterList(params)
        .then(async (res) => {
          if (res.flag == 0) {
            const array = JSON.parse(localStorage.getItem("chapterList"));
            if (res.flag == 0) {
              for (var i = 0; i < res.data.length; i++) {
                res.data[i].pid = res.data[i].chapterId;
                array.push(res.data[i]);
              }
              localStorage.setItem("chapterList", JSON.stringify(array));
              this.directoryList = await this.getTree(array);
            }
          }
        })
        .catch((err) => {
          // this.$Message.error(err.response.data.message);
        });
    },
    getTree(dataList) {
      const tree = [];
      const idMap = new Map();
      dataList.forEach((item) => {
        idMap.set(item.id, item);
      });
      dataList.forEach((item) => {
        if (idMap.has(item.pid)) {
          const parent = idMap.get(item.pid);
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(item);
        } else {
          tree.push(item);
        }
      });
      return JSON.parse(JSON.stringify(tree));
    },
    init() {
      const s = document.createElement("script");
      s.type = "text/javascript";
      s.src = "//web.cdn.openinstall.io/openinstall.js";
      s.addEventListener(
        "load",
        () => {
          var data = OpenInstall.parseUrlParams();
          new OpenInstall(
            {
              appKey: "zpyiil", //appkey参数配置,需要自行替换对应的appkey
              onready: function () {
                var m = this;
                /*在app已安装的情况尝试拉起app*/
                m.schemeWakeup({
                  data: data,
                  channelCode: "test-channelcode",
                });
                window.wakeupOrInstall = function () {
                  this.rnum = this.rnum + 1;
                  m.wakeupOrInstall({
                    data: data,
                    channelCode: "test-channelcode",
                  });
                };
              },
            },
            data
          );
        },
        false
      );
      document.head.appendChild(s);
    },
    openCourse() {
      // console.log(1212)
      // alert('打开课程')
      window.wakeupOrInstall(); //此方法为scheme、Universal Link唤醒以及引导下载的作用（必须调用且不可额外自行跳转下载）
      return false;
    },
    linkCourse() {
      // alert('下载课程')
      // console.log(1212)
      window.wakeupOrInstall(); //此方法为scheme、Universal Link唤醒以及引导下载的作用（必须调用且不可额外自行跳转下载）
      return false;
    },
    sizeTostr(size) {
      var data = "";
      if (size < 0.1 * 1024) {
        //如果小于0.1KB转化成B
        data = size.toFixed(2) + "B";
      } else if (size < 0.1 * 1024 * 1024) {
        //如果小于0.1MB转化成KB
        data = (size / 1024).toFixed(2) + "KB";
      } else if (size < 0.1 * 1024 * 1024 * 1024) {
        //如果小于0.1GB转化成MB
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
      } else {
        //其他转化成GB
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }
      var sizestr = data + "";
      var len = sizestr.indexOf(".");
      var dec = sizestr.substr(len + 1, 2);
      if (dec == "00") {
        //当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
      }
      return sizestr;
    },
    getTime(time) {
      let h = parseInt((time / 60 / 60) % 24);
      h = h < 10 ? "0" + h : h;
      let m = parseInt((time / 60) % 60);
      m = m < 10 ? "0" + m : m;
      let s = parseInt(time % 60);
      s = s < 10 ? "0" + s : s;
      // 作为返回值返回
      h = h > 0 ? h + ":" : "";
      m = m > 0 ? m + ":" : "";
      return h + m + s;
    },
    getClass(item) {
      const name = item.typeText;
      let cs = "";
      switch (name) {
        case "视频":
          cs = "video";
          break;
        case "PPT":
          cs = "ppt";
          break;
        case "PPTX":
          cs = "ppt";
          break;
        case "笔记":
          cs = "note";
          break;
        case "交互实验":
          cs = "experiment";
          break;
        case "测验":
          cs = "test";
          break;
        default:
          cs = "img";
          break;
      }
      return cs;
    },
    isCover(url) {
      let path = "";
      if (!url) {
        return path;
      }
      if (url.indexOf("https://") != -1) {
        path = url;
      } else {
        path = "https://i.zmylschool.com" + url;
      }
      return path;
    },
  },
};
</script>

<style lang='scss' scoped>
</style>
